package top.zhouze.common.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author 周仄
 * @since 2024/1/2 10:48
 */
public class ReflectUtil {

    public static<T> Class<T> getGenericClass(Object obj,int order) {
        return getGenericClass(obj.getClass(),order);
    }

    @SuppressWarnings({"unchecked"})
    public static<T> Class<T> getGenericClass(Class<?> cls,int order) {
        Type type = cls.getGenericSuperclass();
        while (true) {
            if (type instanceof ParameterizedType) {
                return (Class<T>) ((ParameterizedType)type).getActualTypeArguments()[order];
            }else if (type instanceof Class) {
                type = ((Class<?>)type).getGenericSuperclass();
            }else {
                return null;
            }
        }
    }
}
